<!--
 * @description 平台商城-兑换券
 * @author dumeng
 * @date 2021/7/28
 -->
<template>
  <div class="ptdhq-page">
    <el-form ref="ptdhqForm" :model="form" :rules="rules" label-width="180px">
      <el-form-item label="兑换券" prop="classifType2">
        <div class="dhq">
          <el-select
            v-model="form.classifType2"
            placeholder="请选择"
            style="width: 100%"
            :disabled="!!id"
            @change="handleCouponsChange"
          >
            <el-option
              v-for="(item, index) in couponsList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span v-if="!id" class="tip">
            如果兑换券不存在，请先创建兑换券。兑换券创建后需要商家审核，请线下联系商家审核。点击这里
            <el-button type="text" @click="toCoupons">去创建></el-button>
            兑换券。
          </span>
          <i class="el-icon-refresh refresh-i" @click="refresh" />
        </div>

      </el-form-item>
      <el-form-item label="兑换券领取起止时间" prop="receiveTime">
        <el-date-picker
          v-model="form.receiveTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
          :style="{width:'100%'}"
          type="datetimerange"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="兑换券使用起止时间" prop="useTime">
        <el-date-picker
          v-model="form.useTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
          disabled
          :style="{width:'100%'}"
          type="datetimerange"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="使用说明" prop="explain">
        <el-input
          v-model="form.explain"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6 }"
          placeholder="请输入使用说明"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import { queryCoupons } from '../api/index'
import excoupon from '../../excoupon/pages/index'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'Ptdhq',
  components: { excoupon },
  directives: { elDragDialog },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      couponsList: [],
      form: {
        classifType2: '',
        receiveTime: '',
        useTime: '',
        explain: ''
      },
      rules: {
        classifType2: [{ required: true, message: '请选择兑换券', trigger: 'change' }],
        receiveTime: [{ required: true, message: '请选择兑换券领取起止时间', trigger: 'change' }],
        useTime: [{ required: true, message: '请选择兑换券使用起止时间', trigger: 'change' }]
      }
    }
  },
  async created() {
    this.couponsList = await this.getCoupons()
    if (JSON.stringify(this.data) !== '{}') {
      for (const i in this.form) {
        this.$set(this.form, i, this.data[i] || '')
      }
      this.form.receiveTime = [this.data.receiveStarttime, this.data.receiveEndtime]
      this.form.useTime = [this.data.expirationStartdate, this.data.expirationDate]
      delete this.form.receiveStarttime
      delete this.form.receiveEndtime
      delete this.form.expirationStartdate
      delete this.form.expirationDate
    }
  },
  methods: {
    /**
     * 创建兑换券
     */
    toCoupons() {
      this.$emit('saveForm', this.form) // 通知父组件保存from
      this.$router.push({ path: this.$filterPath('manage'), query: { t: 'c', pt: 'ptdhq', c: this.$route.query.t }})
    },
    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },
    handleCouponsChange(value) {
      const obj = this.couponsList.find(a => a.id === value)
      this.$alert(`您选择的兑换券是：${obj.name}，兑换券数量为：${obj.total}，审核状态为：${obj.auditStatusValue}，使用状态为：${obj.statusValue}，
        ${obj.startUseTime ? '有效期是：' + this.formatTime(obj.startUseTime) + '至' : ''}
        ${obj.endUseTime ? this.formatTime(obj.endUseTime) + ']' : ''}`, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          this.$set(this.form, 'receiveTime', [obj.startUseTime, obj.endUseTime])
          this.$set(this.form, 'useTime', [obj.startUseTime, obj.endUseTime])
        }
      })
    },
    /**
     * 获取兑换券列表
     * @returns {Promise<unknown>}
     */
    getCoupons() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryCoupons({
          auditStatus: 'COUPONAUSTATUS03'
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}-${a.total}[${a.statusValue}]${a.startUseTime ? '[' + this.formatTime(a.startUseTime) + '至' : ''}${a.endUseTime ? this.formatTime(a.endUseTime) + ']' : ''}`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    validateForm() {
      return new Promise((resolve) => {
        this.$refs['ptdhqForm'].validate((valid) => {
          if (valid) {
            const query = {
              classifType2: this.form.classifType2,
              explain: this.form.explain,
              receiveStarttime: this.form.receiveTime ? this.form.receiveTime[0] : '',
              receiveEndtime: this.form.receiveTime ? this.form.receiveTime[1] : '',
              expirationStartdate: this.form.useTime ? this.form.useTime[0] : '',
              expirationDate: this.form.useTime ? this.form.useTime[1] : ''
            }
            if (new Date(query.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(query.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券已过期，请选择其他兑换券！',
                type: 'warning'
              })
              return
            }
            resolve(query)
          } else {
            resolve('')
          }
        })
      })
    },
    async refresh() {
      this.couponsList = await this.getCoupons()
    }
  }
}
</script>

<style scoped lang="scss">
  .tip{
    color: #666;
  }
  .dhq{
  position: relative;
  .refresh-i{
    color:#ccc;
    padding-left:8px;
    cursor:pointer;
    position: absolute;
    right:-28px;
    top:5px;
    font-size: 26px;
  }
}
</style>
